package hydrap2p.search.ubuntu;

import hydrap2p.logging.Level;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class DNSLookup {

	private static Map<String, String[]> cache = new TreeMap<String, String[]>();
	
	public static String[] getIP(URL url)
	{
		if (url==null)
			return null;
		if (!cache.containsKey(url.getHost()))
		{
			InetAddress[] inets=null;
			String[] ips=null;
			try {
				inets=InetAddress.getAllByName(url.getHost());
			} catch (UnknownHostException e) {
				UbuntuLogging.log(Level.MISHAP, "Ubuntu Search - DNS Lookup", "Could not look up "+url.getHost());
				ips=new String[0];
			}
			if (ips==null)
			{
				ips=new String[inets.length];
				int i=0;
				for (InetAddress inet : inets)
				{
					ips[i++]=inet.getHostAddress();
				}
			}
			cache.put(url.getHost(), ips);
		}
		/*
		else
			UbuntuLogging.log(Level.DEBUG, "Ubuntu Search - DNS Lookup", "Using cached lookup of "+url.getHost());
		*/
		
		return cache.get(url.getHost());
		
	}
}
